package com.nwpu.coursesupport.service.imple;

import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

@Service
public class QQEmailService {

    String sender = "2147002742@qq.com";
    String code = "zuxdmcxcxbmdehjf";


    public void TaskSubmitNotify(){

    }
    public void sendQQMail(String receiver, String title, String content, File[] files) throws MessagingException, UnsupportedEncodingException {
        String contentType = "text/html;charset=UTF-8";
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", "smtp.qq.com");
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.debug", "true");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.ssl.enable", "true");
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(sender, code);
            }
        });
        Message message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(sender));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
            message.setSubject(title);

            // 是否存在附件
            if (null != files && files.length > 0) {
                MimeMultipart multipart = new MimeMultipart();

                BodyPart contentPart = new MimeBodyPart();
                contentPart.setContent(content, contentType);
                multipart.addBodyPart(contentPart);

                for (File file : files) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    DataHandler dh2 = new DataHandler(new FileDataSource(file));
                    attachment.setDataHandler(dh2);
                    attachment.setFileName(MimeUtility.encodeText(dh2.getName()));
                    multipart.addBodyPart(attachment);
                }
                multipart.setSubType("mixed");

                message.setContent(multipart);
                message.saveChanges();
            }
            // 普通
            else {
                message.setContent(content, contentType);
            }

            Transport transport = session.getTransport();
            transport.connect(sender, code);
            Transport.send(message);
        } catch (UnsupportedEncodingException e) {
            throw e;
        } catch (NoSuchProviderException e) {
            throw e;
        } catch (MessagingException e) {
            throw e;
        }

    }
}
